package user

import (
	"errors"
	"fmt"
	"io"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/common"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/tool"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/excel"

	"gitee.com/liuxuezhan/ar-platform/base-common/result"

	agentClient "gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/client"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 会员管理 - 下级会员导出
func NextLevelExportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UserChildSearchRequest
		if err := httpx.Parse(r, &req); err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		rpcReq := &userrpc.UserChildSearchRequest{
			Page:             req.Page,
			PageSize:         req.PageSize,
			Id:               req.AgentId,
			ChildId:          req.ChildId,
			Nickname:         req.Nickname,
			MinLevel:         req.MinLevel,
			MaxLevel:         req.MaxLevel,
			RegisterDevice:   req.RegisterDevice,
			Status:           req.Status,
			Order:            req.OrderType,
			RegisterStart:    req.RegisterStart,
			RegisterEnd:      req.RegisterEnd,
			TransactionStart: req.TransactionStart,
			TransactionEnd:   req.TransactionEnd,
			VipLevel:         req.VipLevel,
		}
		client := svcCtx.UserServiceRPC
		stream, err := client.UserChildExport(r.Context(), rpcReq)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		// agent info
		agentResp, err := svcCtx.AgentRPC.GetAgentInfoByUserIds(r.Context(), &agentClient.UserIdsRequest{UserIds: []int64{req.AgentId}})
		if err != nil {
			logc.Error(r.Context(), "Agent GetAgentInfoByUserIds rpc call error: %v", err)
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		agentLevel := int64(0)
		if agent, ok := agentResp.Data[req.AgentId]; ok {
			agentLevel = agent.Level
		}

		excelWriter, err := excel.NewExcelWriter()
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}
		defer excelWriter.Close()

		excelWriter.SetHeaders([]string{
			"会员ID",
			"账号",
			"VIP等级",
			"上级ID",
			"相对层级",
			"直属下级",
			"全部下级",
			"注册时间",
			"使用状态",
			"在线状态",
			"注册设备",
			"黑名单",
			"下单（金额/次）",
			"充值（金额/次）",
			"提现（金额/次）",
			"返佣（金额/次）", // todo
			"账户余额",     // todo
			"备注",
		})
		index := 2
		for {
			data, err := stream.Recv()
			if errors.Is(err, io.EOF) {
				break
			}
			if err != nil {
				result.HttpErrorResult(r.Context(), w, err)
				return
			}

			t1 := fmt.Sprintf("%.2f/%d/%d", data.BetAmount, data.BetCount, data.BetUserCount)
			t2 := fmt.Sprintf("%.2f/%d/%d", data.RechargeAmount, data.RechargeCount, data.RechargeUserCount)
			t3 := fmt.Sprintf("%.2f/%d/%d", data.WithdrawAmount, data.WithdrawCount, data.WithdrawUserCount)
			excelWriter.AddRow(index, []interface{}{
				data.Id,
				data.Account,
				data.VipLevel,
				data.ParentId,
				data.Level - int32(agentLevel),
				data.ChildNum,
				data.AllChildNum,
				tool.TimeFormat(data.RegistAt, ""),
				common.EnumUserStatus[data.Status],
				common.EnumUserOnline[data.IsOnline],
				data.RegisterDevice,
				common.EnumUserBlacklist[data.IsBlacklist],
				t1,
				t2,
				t3,
				"", // todo
				data.Balance,
				data.Remark,
			})
			index++
		}

		excelWriter.Flush()

		// download
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
		excelWriter.Write(w)
	}
}
